/**
 * Created by spatra on 14-12-5.
 */

define(['projectJS/module'], function(projectModule){

  /**
   * 任务查看的控制器
   */
  projectModule.controller('TaskController',
    ['$rootScope', '$scope', '$stateParams', '$state', 'taskSet', 'taskStatusSet', 'TaskService', '$modal', 'MemberService', 'taskConditions', 'TaskPriorityService', 'InitRightHeightService','ClassHelperService',
      function($rootScope, $scope, $stateParams, $state, taskSet, taskStatusSet, TaskService, $modal, MemberService, taskConditions, TaskPriorityService, InitRightHeightService, ClassHelperService){

        //设置父级资源
        TaskService.accessor['setParentResourceId']($stateParams);
        /*
        初始化控制器作用域内使用到的变量
         */
        $scope.taskStatusSet = taskStatusSet;   //任务状态的数据集合
        $scope.taskSet = taskSet;


        $scope.currentProjectId = $stateParams['projectId'];  //设置当前的项目id
        $scope.conditions = taskConditions;   //加载任务的条件筛选项
        $scope.conditionObj = {};   //按条件筛选任务时使用的添加集合对象

        //滚动监听
        $rootScope.$on('load:status', function(event, currentStatusId){
          $scope.$apply(function(){
            var pagination = $scope.taskSet[currentStatusId].pagination;
            pagination.loadDataWhenToBottom(reloadTaskSet, {
              currentStatusId: currentStatusId
            });
          });
        });

        //任务内容高度设置
        InitRightHeightService.init('task-content');


        /**
         * 重新加载任务集合
         * @param obj:{currentStatusId,conditionObj}
         *    currentStatusId不设置时全部加载
         */
        function reloadTaskSet(obj){
          var params = {
            //@workaround:暂时设死18个
            per_page: 18,
            page: 1,
            group: true
          };

          if(obj.currentStatusId){
            //如果有指定currentStatusId时
            var currentStatusId = obj.currentStatusId;
            var pagination = $scope.taskSet[currentStatusId].pagination;
            var currentStatusLabel = $scope.taskStatusSet[currentStatusId].name;

            params.per_page = pagination.itemsPerPage * pagination.currentPage;

          }
          //如果有筛选对象,则合并筛选对象到提交数据

          if(obj.currentStatusId){
            params.status = currentStatusLabel;
          }

          if(obj.priorityId){
            params.priority_id = obj.priorityId;
          }

          if(obj.conditionObj){
            ClassHelperService.update(obj.conditionObj, params);
          }


          function getLabelId(taskStatusSet){
            var labelIdSet = {};
            for(var id in taskStatusSet){
              labelIdSet[taskStatusSet[id].name] = id;
            }
            return labelIdSet;
          }

          var labelIdSet = getLabelId($scope.taskStatusSet);


          TaskService.accessor.get({
            params: params
          })
            .success(function(data){
              if(obj.currentStatusId){
                $scope.taskSet[currentStatusId]['data'] = data[currentStatusLabel].data;

                pagination.setShowLoading(false);
              }
              else{

                for(var statusLabel in data){
                  var statusId = labelIdSet[statusLabel];
                  $scope.taskSet[statusId]['data'] = data[statusLabel].data;
                }

              }
            })
            .error(function(data){

              console.error(data.error);
            });
        }

        /*
          建立监听，当其他部分的操作导致任务列表数据发生变动时，此处会刷新显示
          @params: transObj: {currentStatusId}
         */
        $rootScope.$on('task:reload', function(event, transObj){
          if(!transObj){
            transObj = {};
          }
          reloadTaskSet(transObj);
        });

        /*
          监听筛选条件的变化，并执行重新
         */

        $scope.$watch('conditionObj', function(){
          reloadTaskSet({
            conditionObj: $scope.conditionObj
          });
        }, true);
        /*
          当用户点击指定任务时，加载详细的任务信息
         */
        $scope.showBriefTask = function(taskObj){
          if( taskObj.loadDetails ) return;

          //TaskService.showWithCache( taskObj.id )
          TaskService.accessor.show(taskObj.id)
            .success(function(data){
              $.extend(taskObj, data);
              taskObj.loadDetails = true;
            })
            .error(function(data){
              $scope.$emit('message:error',{
                title: '获取具体任务信息失败',
                msg: data.error
              });

            });
        };

        /*
          创建新的任务
         */
        $scope.createTask = function() {
          $scope.createTaskModalInstance = $modal.open({
            templateUrl: 'ngApp/project/tpls/createTaskModal.html',
            controller: 'CreateTaskModalController',
            size: 'lg',
            resolve: {
              projectMemberList: function(){
                return MemberService.accessor.get()
                  .then(function(resp){
                    var projectMembers = resp.data.members;
                    projectMembers.unshift(resp.data.creater);
                    return projectMembers;
                  },
                  function(data){
                    $scope.$emit('message:error',{
                      title: '加载成员列表出错'
                    })
                  });
              },
              priorityList: function(){
                return TaskPriorityService.accessor.get()
                  .then(function(resp){ return resp.data; }, function(resp){
                    console.error(resp.data);
                    alert('加载任务优先级列表出错');
                  })
              },
              parentTaskInfo: function(){
                return null;
              }
            }
          });//End of --> $scope.createTaskModalInstance

          //用于处理新建任务所关联的模态框
          $scope.createTaskModalInstance.result
            .then(function(taskData){
              TaskService.accessor.store(taskData)
                .success(function(data){
                  $scope.$emit('message:success',{
                    title: '任务创建成功'
                  });
                  $scope.$emit('task:reload', {
                    //@workaround:暂时设死为1
                    currentStatusId: 1,
                    priorityId: data['priority_id']
                  });

                })
                .error(function(){
                  $scope.$emit('message:error',{
                    title: '任务创建失败'
                  });
                })
            });//End of --> $scope.createTaskModalInstance.result


        };//End of --> $scope.createTask

        //跳转到task列表的状态
        $scope.goToTaskState = function(){
          $state.go('project.show.task', $stateParams);
        };

  }]);  //End of --> TaskController

  /**
   * 具体任务框的控制器
   */
  projectModule.controller('TaskInfoController', ['$scope', '$rootScope', '$location', 'TaskService', '$stateParams', 'TaskStatusService', '$state',
  function($scope, $rootScope, $location, TaskService, $stateParams, TaskStatusService, $state){
    $scope.showInput = false;
    $scope.currentProjectId = $stateParams['projectId'];  //设置当前的项目id

    $scope.curStateName = $state.current.name;
    var mainStatePattern = /project.show(\.[\w]+)/;
    $scope.mainStateName = $state.current.name.match(mainStatePattern)[0];

    var loadTaskInfo = function() {

      TaskService.accessor['setParentResourceId']($stateParams);
      TaskService.accessor.show($stateParams.taskId)
        .success(function(data){
          $scope.currentSpecificTask = data;
        })
        .error(function(data){
          console.error(data);
        });

      TaskStatusService.accessor.get()
        .success(function(data){
          $scope.taskStatusList = data;
        })
        .error(function(data){
          console.error(data);
        });

    };

    loadTaskInfo();


    //监听task:reload,刷新任务内容
    $rootScope.$on('task:reload', function(event){
      if($stateParams.taskId){
        loadTaskInfo();
      }
    });

    $scope.changeTaskStatus = function(taskStatusId){

      TaskService.accessor.update($scope.currentSpecificTask.baseInfo.id, {
        'status_id': taskStatusId
      })
        .success(function(){
          $scope.$emit('task:reload');
          $scope.$emit('message:success', {
            title: '任务状态改变成功'
          })
        })
        .error(function(data){
          if( data.error ){
            $scope.$emit('message:error',{
              title: '出错啦!',
              msg: data.error
            });
          }
          else{
            $scope.$emit('message:error',{
              title: '出错啦!',
              msg: data.error
            });
          }
        });
    };

  }]);//End of --> TaskInfoController
});